import React, { useState, useRef } from "react";
import {
  Button,
  Input,
  Slider,
  ColorPicker,
  Radio,
  Space,
  message,
  Upload,
} from "antd";
import { CloudUploadOutlined } from "@ant-design/icons";
import type { RadioChangeEvent } from "antd";
import type { UploadChangeParam, UploadFile } from "antd/es/upload/interface";
import ToolTitle from "@/components/ToolTitle";
import { imgToolsData } from "@/components/ToolsData";

const ImgWatermark: React.FC = () => {
  const [sourceImage, setSourceImage] = useState<string | null>(null);
  const [watermarkText, setWatermarkText] = useState<string>("水印文字");
  const [watermarkOpacity, setWatermarkOpacity] = useState<number>(50);
  const [watermarkColor, setWatermarkColor] = useState<string>("#000000");
  const [watermarkSize, setWatermarkSize] = useState<number>(24);
  const [watermarkPosition, setWatermarkPosition] = useState<string>("center");
  const [watermarkType, setWatermarkType] = useState<string>("text");
  const [watermarkImage, setWatermarkImage] = useState<string | null>(null);
  const [watermarkRotation, setWatermarkRotation] = useState<number>(0);
  const [watermarkRepeat, setWatermarkRepeat] = useState<string>("single");
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [watermarkApplied, setWatermarkApplied] = useState<boolean>(false);

  // 处理图片上传
  const handleImageUpload = (info: UploadChangeParam<UploadFile<any>>) => {
    if (info.file.status === "uploading") {
      return;
    }

    if (info.file.status === "error") {
      message.error(`${info.file.name} 文件上传失败`);
      return;
    }

    // 无论文件状态如何,都尝试读取文件
    const file = info.file.originFileObj;
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          setSourceImage(e.target.result as string);
          // 创建新的Image对象用于获取图片尺寸
          const img = new Image();
          img.onload = () => {
            if (canvasRef.current) {
              canvasRef.current.width = img.width;
              canvasRef.current.height = img.height;
            }
          };
          img.src = e.target.result as string;
        }
      };
      reader.readAsDataURL(file);
    }
  };

  // 处理水印图片上传
  const handleWatermarkImageUpload = (
    info: UploadChangeParam<UploadFile<any>>
  ) => {
    // 无论文件状态如何,都尝试读取文件
    const file = info.file.originFileObj;
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          setWatermarkImage(e.target.result as string);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  // 处理水印类型切换
  const handleWatermarkTypeChange = (e: RadioChangeEvent) => {
    setWatermarkType(e.target.value);
  };

  // 处理水印位置切换
  const handlePositionChange = (e: RadioChangeEvent) => {
    setWatermarkPosition(e.target.value);
  };

  // 应用水印
  const applyWatermark = () => {
    if (!sourceImage) {
      message.error("请先上传图片");
      return;
    }

    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const img = new Image();
    img.onload = () => {
      // 设置画布大小
      canvas.width = img.width;
      canvas.height = img.height;

      // 绘制原图
      ctx.drawImage(img, 0, 0);

      // 设置水印透明度
      ctx.globalAlpha = watermarkOpacity / 100;

      // 根据水印类型绘制水印
      if (watermarkType === "text") {
        // 文字水印
        ctx.font = `${watermarkSize}px Arial`;
        ctx.fillStyle = watermarkColor;

        // 计算文字尺寸
        const textMetrics = ctx.measureText(watermarkText);
        const textWidth = textMetrics.width;
        const textHeight = watermarkSize;

        if (watermarkRepeat === "horizontal") {
          // 水平平铺模式
          const padding = 300; // 水印之间的间距
          const stepX = textWidth + padding;

          // 计算需要绘制的列数
          const cols = Math.ceil(canvas.width / stepX) + 1;

          // 根据位置确定Y坐标
          let y = 40;
          switch (watermarkPosition) {
            case "topLeft":
            case "topRight":
              y = 40;
              break;
            case "center":
              y = canvas.height / 2;
              break;
            case "bottomLeft":
            case "bottomRight":
              y = canvas.height - 20;
              break;
          }

          // 水平重复绘制水印
          for (let col = 0; col < cols; col++) {
            const x = col * stepX;

            // 应用旋转
            if (watermarkRotation !== 0) {
              // 保存当前状态
              ctx.save();

              // 移动到旋转中心点（文字中心）
              const centerX = x + textWidth / 2;
              const centerY = y - textHeight / 2;
              ctx.translate(centerX, centerY);

              // 旋转
              ctx.rotate((watermarkRotation * Math.PI) / 180);

              // 绘制文字（相对于旋转后的坐标系）
              ctx.fillText(watermarkText, -textWidth / 2, textHeight / 4);

              // 恢复状态
              ctx.restore();
            } else {
              // 不旋转时直接绘制
              ctx.fillText(watermarkText, x, y);
            }
          }
        } else if (watermarkRepeat === "vertical") {
          // 垂直平铺模式
          const padding = 300; // 水印之间的间距
          const stepY = textHeight + padding;

          // 计算需要绘制的行数
          const rows = Math.ceil(canvas.height / stepY) + 1;

          // 根据位置确定X坐标
          let x = 20;
          switch (watermarkPosition) {
            case "topLeft":
            case "bottomLeft":
              x = 20;
              break;
            case "center":
              x = (canvas.width - textWidth) / 2;
              break;
            case "topRight":
            case "bottomRight":
              x = canvas.width - textWidth - 20;
              break;
          }

          // 垂直重复绘制水印
          for (let row = 0; row < rows; row++) {
            const y = (row + 1) * stepY;

            // 应用旋转
            if (watermarkRotation !== 0) {
              // 保存当前状态
              ctx.save();

              // 移动到旋转中心点（文字中心）
              const centerX = x + textWidth / 2;
              const centerY = y - textHeight / 2;
              ctx.translate(centerX, centerY);

              // 旋转
              ctx.rotate((watermarkRotation * Math.PI) / 180);

              // 绘制文字（相对于旋转后的坐标系）
              ctx.fillText(watermarkText, -textWidth / 2, textHeight / 4);

              // 恢复状态
              ctx.restore();
            } else {
              // 不旋转时直接绘制
              ctx.fillText(watermarkText, x, y);
            }
          }
        } else {
          // 单个水印模式 - 根据位置设置水印
          let x = 20;
          let y = 40;

          switch (watermarkPosition) {
            case "topLeft":
              x = 20;
              y = 40;
              break;
            case "topRight":
              x = canvas.width - textWidth - 20;
              y = 40;
              break;
            case "center":
              x = (canvas.width - textWidth) / 2;
              y = canvas.height / 2;
              break;
            case "bottomLeft":
              x = 20;
              y = canvas.height - 20;
              break;
            case "bottomRight":
              x = canvas.width - textWidth - 20;
              y = canvas.height - 20;
              break;
          }

          // 应用旋转
          if (watermarkRotation !== 0) {
            // 保存当前状态
            ctx.save();

            // 移动到旋转中心点（文字中心）
            const centerX = x + textWidth / 2;
            const centerY = y - textHeight / 2;
            ctx.translate(centerX, centerY);

            // 旋转
            ctx.rotate((watermarkRotation * Math.PI) / 180);

            // 绘制文字（相对于旋转后的坐标系）
            ctx.fillText(watermarkText, -textWidth / 2, textHeight / 4);

            // 恢复状态
            ctx.restore();
          } else {
            // 不旋转时直接绘制
            ctx.fillText(watermarkText, x, y);
          }
        }

        // 设置应用标志 - 放在这里确保文字水印能立即显示结果
        setWatermarkApplied(true);
      } else if (watermarkType === "image" && watermarkImage) {
        // 图片水印
        const wmImg = new Image();
        wmImg.onload = () => {
          // 设置水印图片大小
          const wmWidth = wmImg.width * (watermarkSize / 24);
          const wmHeight = wmImg.height * (watermarkSize / 24);

          // 根据位置设置水印
          let x = 20;
          let y = 20;

          switch (watermarkPosition) {
            case "topLeft":
              x = 20;
              y = 20;
              break;
            case "topRight":
              x = canvas.width - wmWidth - 20;
              y = 20;
              break;
            case "center":
              x = (canvas.width - wmWidth) / 2;
              y = (canvas.height - wmHeight) / 2;
              break;
            case "bottomLeft":
              x = 20;
              y = canvas.height - wmHeight - 20;
              break;
            case "bottomRight":
              x = canvas.width - wmWidth - 20;
              y = canvas.height - wmHeight - 20;
              break;
          }

          // 应用旋转
          if (watermarkRotation !== 0) {
            // 保存当前状态
            ctx.save();

            // 移动到旋转中心点（图片中心）
            const centerX = x + wmWidth / 2;
            const centerY = y + wmHeight / 2;
            ctx.translate(centerX, centerY);

            // 旋转
            ctx.rotate((watermarkRotation * Math.PI) / 180);

            // 绘制图片（相对于旋转后的坐标系）
            ctx.drawImage(
              wmImg,
              -wmWidth / 2,
              -wmHeight / 2,
              wmWidth,
              wmHeight
            );

            // 恢复状态
            ctx.restore();
          } else {
            // 不旋转时直接绘制
            ctx.drawImage(wmImg, x, y, wmWidth, wmHeight);
          }

          // 设置应用标志 - 在水印图片加载完成后设置
          setWatermarkApplied(true);
        };
        wmImg.src = watermarkImage;
        // 如果水印图片加载失败，仍然显示带文字的结果
        wmImg.onerror = () => {
          message.error("水印图片加载失败");
          setWatermarkApplied(true);
        };
      } else {
        // 如果没有选择水印图片，仍然显示原图
        setWatermarkApplied(true);
      }
    };

    // 图片加载错误处理
    img.onerror = () => {
      message.error("原图加载失败");
    };

    img.src = sourceImage;
  };

  // 下载处理后的图片
  const downloadImage = (format: string) => {
    if (!canvasRef.current) return;

    let mimeType = "image/png";
    let extension = "png";

    if (format === "jpg") {
      mimeType = "image/jpeg";
      extension = "jpg";
    } else if (format === "webp") {
      mimeType = "image/webp";
      extension = "webp";
    }

    const dataUrl = canvasRef.current.toDataURL(mimeType);
    const link = document.createElement("a");
    link.download = `watermarked_image.${extension}`;
    link.href = dataUrl;
    link.click();
  };

  return (
    <div className="max-w-6xl mx-auto px-4 py-6">
      <ToolTitle
        title={
          imgToolsData.find((item) => item.title === "水印添加")?.title || ""
        }
        description={
          imgToolsData.find((item) => item.title === "水印添加")?.description ||
          ""
        }
      />

      <div className="flex flex-col md:flex-row gap-6 mb-6">
        <div className="flex-1 border border-dashed border-gray-300 rounded-md bg-gray-50 min-h-[400px] flex items-center justify-center overflow-hidden">
          {!sourceImage ? (
            <Upload.Dragger
              name="file"
              multiple={false}
              showUploadList={false}
              onChange={handleImageUpload}
              accept="image/*"
              className="w-full h-full"
              beforeUpload={(file) => {
                const isImage = /image\/(jpeg|jpg|png|gif|webp|svg|ico)/.test(
                  file.type
                );
                if (!isImage) {
                  message.error("只能上传图片文件!");
                }
                return isImage || Upload.LIST_IGNORE;
              }}
              customRequest={({ file, onSuccess }) => {
                console.log("file", file);
                // 模拟上传成功
                setTimeout(() => {
                  if (onSuccess) {
                    onSuccess("ok");
                  }
                }, 0);
              }}
            >
              <p className="text-5xl text-gray-400">
                <CloudUploadOutlined />
              </p>
              <p className="text-gray-600">
                拖拽图片文件到此处 或 点击选择文件
              </p>
            </Upload.Dragger>
          ) : (
            <div className="w-full h-full relative flex justify-center items-center">
              <div className="max-w-full max-h-[400px] flex justify-center items-center">
                <img
                  src={sourceImage}
                  alt="预览图"
                  className="max-w-full max-h-[400px] object-contain"
                  style={{ display: watermarkApplied ? "none" : "block" }}
                />
                <canvas
                  ref={canvasRef}
                  style={{
                    maxWidth: "100%",
                    maxHeight: "400px",
                    objectFit: "contain",
                    display: watermarkApplied ? "block" : "none",
                  }}
                />
              </div>
              <div className="absolute top-2 right-2 flex gap-2">
                {watermarkApplied && (
                  <Button
                    type="primary"
                    size="small"
                    onClick={() => {
                      setWatermarkApplied(false);
                    }}
                  >
                    原图
                  </Button>
                )}
                <Button
                  type="primary"
                  danger
                  size="small"
                  onClick={() => {
                    setSourceImage(null);
                    setWatermarkApplied(false);
                  }}
                >
                  删除
                </Button>
              </div>
            </div>
          )}
        </div>

        <div className="flex-1 bg-gray-100 p-5 rounded-md">
          <div className="mb-5">
            <h3 className="text-base font-medium mb-2">水印类型</h3>
            <Radio.Group
              onChange={handleWatermarkTypeChange}
              value={watermarkType}
            >
              <Radio value="text">文字水印</Radio>
              <Radio value="image">图片水印</Radio>
            </Radio.Group>
          </div>

          {watermarkType === "text" ? (
            <div className="mb-5">
              <h3 className="text-base font-medium mb-2">水印文字</h3>
              <Input
                value={watermarkText}
                onChange={(e) => setWatermarkText(e.target.value)}
                placeholder="请输入水印文字"
                className="mb-4"
              />

              <h3 className="text-base font-medium mb-2">字体颜色</h3>
              <ColorPicker
                value={watermarkColor}
                onChange={(color) => setWatermarkColor(color.toHexString())}
                className="mb-4"
              />

              <h3 className="text-base font-medium mb-2">字体大小</h3>
              <Slider
                min={12}
                max={72}
                value={watermarkSize}
                onChange={(value) => setWatermarkSize(value)}
                className="mb-4"
              />

              <h3 className="text-base font-medium mb-2">文字旋转角度</h3>
              <Slider
                min={-180}
                max={180}
                value={watermarkRotation}
                onChange={(value) => setWatermarkRotation(value)}
                tooltip={{
                  formatter: (value) => `${value}°`,
                }}
                marks={{
                  "-180": "-180°",
                  "-90": "-90°",
                  "0": "0°",
                  "90": "90°",
                  "180": "180°",
                }}
              />

              <h3 className="text-base font-medium mb-2">重复水印</h3>
              <Radio.Group
                onChange={(e) => setWatermarkRepeat(e.target.value)}
                value={watermarkRepeat}
                className="mb-4"
              >
                <Radio value="single">单个水印</Radio>
                <Radio value="horizontal">水平平铺</Radio>
                <Radio value="vertical">垂直平铺</Radio>
              </Radio.Group>
            </div>
          ) : (
            <div className="mb-5">
              <h3 className="text-base font-medium mb-2">水印图片</h3>
              <Upload
                name="watermarkImage"
                showUploadList={false}
                onChange={handleWatermarkImageUpload}
                accept="image/*"
                className="mb-4"
              >
                <Button>选择水印图片</Button>
              </Upload>

              <h3 className="text-base font-medium mb-2">水印大小</h3>
              <Slider
                min={10}
                max={100}
                value={watermarkSize}
                onChange={(value) => setWatermarkSize(value)}
                className="mb-4"
              />

              <h3 className="text-base font-medium mb-2">图片旋转角度</h3>
              <Slider
                min={-180}
                max={180}
                value={watermarkRotation}
                onChange={(value) => setWatermarkRotation(value)}
                tooltip={{
                  formatter: (value) => `${value}°`,
                }}
                marks={{
                  "-180": "-180°",
                  "-90": "-90°",
                  "0": "0°",
                  "90": "90°",
                  "180": "180°",
                }}
              />
            </div>
          )}

          <div className="mb-5">
            <h3 className="text-base font-medium mb-2">水印位置</h3>
            <Radio.Group
              onChange={handlePositionChange}
              value={watermarkPosition}
            >
              <Space direction="vertical">
                <Radio value="topLeft">左上角</Radio>
                <Radio value="topRight">右上角</Radio>
                <Radio value="center">居中</Radio>
                <Radio value="bottomLeft">左下角</Radio>
                <Radio value="bottomRight">右下角</Radio>
              </Space>
            </Radio.Group>
          </div>

          <div className="mb-5">
            <h3 className="text-base font-medium mb-2">水印透明度</h3>
            <Slider
              min={10}
              max={100}
              value={watermarkOpacity}
              onChange={(value) => setWatermarkOpacity(value)}
            />
          </div>

          <div className="mb-5">
            <Button type="primary" onClick={applyWatermark} className="mr-2">
              应用水印
            </Button>
          </div>
        </div>
      </div>

      <div className="flex justify-center flex-wrap gap-3">
        <Button onClick={() => downloadImage("png")} className="min-w-[150px]">
          下载图片 .png
        </Button>
        <Button onClick={() => downloadImage("jpg")} className="min-w-[150px]">
          下载图片 .jpg
        </Button>
        <Button onClick={() => downloadImage("webp")} className="min-w-[150px]">
          下载图片 .webp
        </Button>
      </div>
    </div>
  );
};

export default ImgWatermark;
